<template>
  <div class="main-container">
    <!-- 顶部导航栏 -->
    <el-menu
      :default-active="activeMenu"
      active-text-color="#e74c3c"
      class="header-menu"
      mode="horizontal"
      text-color="black"
      @select="handleMenuSelect"
    >
      <div class="menu-left">
        <el-menu-item index="home">今日推荐</el-menu-item>
        <el-menu-item index="library">音乐库</el-menu-item>
        <el-menu-item index="forum">乐享论坛</el-menu-item>
      </div>

      <div class="menu-right">
        <el-input
          v-model="searchText"
          :prefix-icon="Search"
          class="search-input"
          clearable
          placeholder="搜索音乐或帖子"
        />
        <template v-if="username">
          <el-dropdown @command="handleCommand">
            <div class="user-profile">
              <el-avatar :size="32" :src="avatar || ''" class="user-avatar">
                {{ username?.charAt(0) || '访' }}
              </el-avatar>
              <span class="user-name">{{ username }}</span>
              <el-icon class="el-icon--right">
                <arrow-down />
              </el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人中心</el-dropdown-item>
                <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
        <el-button v-else class="login-btn" type="primary" @click="showLoginDialog = true">
          <el-icon>
            <User />
          </el-icon>
          登录/注册
        </el-button>
      </div>
    </el-menu>

    <!-- 主内容区 -->
    <router-view class="main-content" />

    <!-- 登录注册对话框 -->
    <LoginDialog v-model="showLoginDialog" @login-success="handleLogin" @register-success="handleRegister" />
  </div>
</template>

<script setup>
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores'
import { storeToRefs } from 'pinia'
import { computed, onMounted, ref } from 'vue'
import { ArrowDown, Search, User } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import LoginDialog from '@/components/LoginDialog.vue'
import { oAuthLogout, oAuthTokenParseToken } from '@/api/oAuth.js'

const router = useRouter()
const route = useRoute()

const searchText = ref('')
const showLoginDialog = ref(false)
const userStore = useUserStore()

const { email, username, roles, token, avatar, expires } = storeToRefs(userStore)

const activeMenu = computed(() => {
  const routeName = route.name
  if (routeName?.startsWith('profile')) return 'profile'
  return routeName || '/'
})

onMounted(() => {
  handleParseToken()
})

const handleMenuSelect = index => {
  router.push({ name: index })
}

const handleLogin = val => {
  const basicInfos = val.data
  console.log(basicInfos)
  userStore.setBasicInfo(basicInfos.email, basicInfos.avatar, basicInfos.token, basicInfos.type, basicInfos.expires)
  handleParseToken()
  ElMessage.success('登录成功')
}

const handleRegister = val => {
  ElMessage.success('注册成功')
}

const handleParseToken = async () => {
  if (token.value === '') return
  try {
    const response = await oAuthTokenParseToken(token.value)
    userStore.setFullInfo(response.data.username, response.data.roles, response.data.expires)
  } catch (error) {
    console.log(error)
  }
}

const handleCommand = async command => {
  switch (command) {
    case 'logout':
      await oAuthLogout({
        email: email.value,
        username: username.value
      })
      userStore.removeFullInfos()
      if (route.name?.startsWith('profile')) await router.push('/')
      console.log(activeMenu)
      ElMessage.warning('退出登录')
      break
    case 'profile':
      await router.push('/profile')
      break
  }
}
</script>

<style scoped>
:deep(.el-menu--horizontal .el-menu-item) {
  background-color: transparent !important;
  --el-menu-hover-bg-color: transparent !important;
  --el-menu-active-color: black;
}

.main-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.header-menu {
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  font-weight: bold;
}

.menu-left {
  display: flex;
  align-items: center;
}

.menu-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.search-input {
  width: 300px;
  transition: all 0.3s;
}

.search-input:hover {
  width: 350px;
}

.login-btn {
  background: #e74c3c;
  border-color: #e74c3c;
  padding: 8px 20px;
  transition: all 0.3s;
}

.login-btn:hover {
  background: #c0392b;
  border-color: #c0392b;
  transform: translateY(-2px);
}

.main-content {
  flex: 1;
  background: #f5f6fa;
  padding: 20px;
  overflow-y: auto;
}

.user-profile {
  display: flex;
  align-items: center;
  padding: 0 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.user-avatar {
  margin-right: 8px;
  background-color: #e74c3c;
}

.user-name {
  color: black;
  font-weight: bold;
  margin-right: 6px;
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
